angular.module('newsdetailcontrollers', [])
  .controller("NewsDetailCtrl",function($scope,$state,$timeout,$rootScope,$cordovaStatusbar,$cordovaFileTransfer,$ionicActionSheet,$stateParams,Loading,Toast,ENV,News,NewsComment,Storage,History){

    var messageId=$stateParams['messageId'];
    var memberId ='';
    var items = [];
    var messageIdList = [];
    var pswpElement = document.querySelectorAll('.pswp')[0];
    //进入页面时
    var firstInNewDetails = true;
    $scope.$on('$ionicView.beforeEnter',function(){
      memberId = Storage.get("member").member_id;
      messageIdList = News.getMessageIdList();
      var fromWhere = News.getFromWhere();
      if(fromWhere=='messageIndex'){
        for(i=0;i<messageIdList.length;i++){
          if(messageIdList[i]==messageId){
            index = i;
            break;
          }
        }
      }
      if($scope.newsContent!=undefined){
        NewsComment.getCommentCount(messageId,memberId);
      }
      if(firstInNewDetails){
        firstInNewDetails = false;
        Loading.showLoading();
      }
    });

    News.getNewsContent(messageId,memberId);

    /*********************页面切换************/
    //获取到手指下落的Index
    var index = 0;
    //向左滑动
    $scope.swipeLeft = function(){
      var fromWhere = News.getFromWhere();
      if(fromWhere=='messageIndex'){
        var nextPage = index+1;
        if(nextPage<messageIdList.length){
          index++;
          $state.go('newsDetails',{'messageId':messageIdList[nextPage]});
        }else if(nextPage>=messageIdList.length){
          Toast.showMessage("已经到最后一篇资讯了");
        }
      }
    }
    //向右滑动
    $scope.swipeRight = function(){
      var fromWhere = News.getFromWhere();
      if(fromWhere=='messageIndex'){
        var prePage = index-1;
        if(prePage>=0){
          index--;
          $state.go('newsDetails',{'messageId':messageIdList[prePage]});
        }else if(prePage<0){
          Toast.showMessage("已经到第一篇资讯了");
        }
      }
    }

    /********************************************/


    $scope.$on('$ionicView.afterEnter',function(){
      $timeout(function(){
         var imgObjList = document.getElementById('newsDetail').getElementsByTagName('img');
        for(i=0;i<imgObjList.length;i++){
          var temp = {
            src:imgObjList[i].src,
            w:imgObjList[i].naturalWidth,
            h:imgObjList[i].naturalHeight
          };
          items.push(temp);
          imgObjList[i].onclick = function(){
            var options = {
              index: i,
              history: false,
              focus: false,
              loop: false,
            /*  pinchToClose:false,
              closeOnVerticalDrag:false,*/
              showAnimationDuration: 100,
              hideAnimationDuration: 100,
              backButtonHideEnabled:true,
              captionAndToolbarFlipPosition:true,
              loadingIndicatorDelay:100
            };
            $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
            $rootScope.gallery.init();
           // $cordovaStatusbar.hide();
          }
        }
      },2000);
      //长按下载
      $rootScope.downloadHomeImg = function(){
        var url = $rootScope.gallery.currItem.src;
        if(url){
          var timestamp=new Date().getTime();
          var targetPath = cordova.file.externalRootDirectory+"winelife/winelife_news_"+timestamp+".jpg";
          var trustHosts = true;
          var options = {};
          $ionicActionSheet.show({
            buttons: [
              {text: '保存到手机相册'}
            ],
            cancelText: '取消',
            buttonClicked: function (index) {
              if(index==0){
                $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
                  .then(function(result) {
                    Toast.showMessage("保存成功");
                  }, function(err) {
                    Toast.showMessage("保存成功");
                  }, function (progress) {
                  });
              }
              return true;
            }
          });
        }
      }
      $rootScope.smallPicture = function(){
        $rootScope.gallery.close();
       // $cordovaStatusbar.show();
      }
    });
    //当service访问网络成功时，调用该方法
    $scope.$on('News.newsDetailUpdated', function() {
      Loading.hideLoading();//隐藏加载框
      $scope.newsContent = News.getContentJson();
    });
    //返回
    $scope.goback = function(){
      var fromWhere = News.getFromWhere();
      if(fromWhere=='messageIndex'){
        $state.go('tab.newsIndex');
      }else if(fromWhere=='myCollect'){
        $state.go('collect-wine');
      }
    }
    //收藏资讯详情
    var collectNewsing = false;//是否已经点击
    $scope.collectNews = function(){
      if(!collectNewsing){
        Loading.showLoading();
        News.collectNews(memberId,messageId);
        collectNewsing = true;
      }else{
        Toast.showMessage("网络请求中，请勿重复操作");
      }
    }
    //当service访问网络成功时，调用该方法
    $scope.$on('News.collectNewsUpdated', function(){
      Loading.hideLoading();
      collectNewsing = false;
      var result = News.getCollectJson();
      $scope.newsContent.mcStatus = result.mcStatus;
      Toast.showMessage(result.mcMsg);
    });
    //给资讯详情点赞
    var likeNewing = false;
    $scope.likeNews = function(){
      if(!likeNewing){
        Loading.showLoading();
        News.likeNews(memberId,messageId);
        likeNewing = true;
      }else{
        Toast.showMessage("网络请求中，请勿重复操作");
      }

    }
    //当service访问网络成功时，调用该方法
    $scope.$on('News.likeNewsUpdated', function(){
      likeNewing =false;
      Loading.hideLoading();
      var result = News.getLikeJson();
      $scope.newsContent.lmStatus = result.lmStatus;
      Toast.showMessage(result.lmMsg);
    });
    //当service访问网络成功时，调用该方法
    $scope.$on('News.CommentCountUpdated', function(){
      var result = NewsComment.getCommetCountJson();
      $scope.newsContent.message_comment_num = result.message_comment_num;
      $scope.newsContent.lmStatus = result.lmStatus;
        $scope.newsContent.mcStatus = result.mcStatus;
    });
  })

  .controller("NewsCommentCtrl",function($scope,$stateParams,$ionicPopup,Loading,Toast,$ionicPlatform,NewsComment,ENV,Storage,History){

    var messageId=$stateParams['messageId'];
    var memberId = '';
   // $scope.messageTitle = Storage.get("messageTitle");
    $scope.picPath = ENV.picPath;
    var isFirstIn = true;
    $scope.$on('$ionicView.beforeEnter',function(){
      memberId = Storage.get('member').member_id;
      //获取评论列表
      if(isFirstIn){
        Loading.showLoading();
        isFirstIn = false;
      }
      NewsComment.getCommentList(messageId,memberId);
    });

    //新增评论
      $scope.comment={
        newComment:''
      };
    //删除评论
    var deleteIndex = '';
    $scope.deleteComment = function(mcommentId,index){
      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px;">确定要删除该评论吗？</p>',
        cancelText: '取消',
        okText: '确定',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          Loading.showLoading();
          NewsComment.deleteComment(mcommentId,memberId,messageId);
          deleteIndex = index;
        }
      });
    }
    $scope.$on('NewsComment.deleteCommentUpdated',function(){
      Loading.hideLoading();
      var result = NewsComment.getDelCommentJson();
      if(result.dmCommentStatus){
        $scope.newsCommentList.splice(deleteIndex,1);
        deleteIndex = '';
      }
      Toast.showMessage(result.dmCommentMsg);
    });
    //返回
    $scope.goback = function(){
      History.goback();
    }
    //下拉刷新
    $scope.doRefresh = function(){
      NewsComment.getCommentList(messageId,memberId);
    }
    //上拉加载
    $scope.loadMore = function(){
      NewsComment.getMoreCommentList(messageId,memberId);
    }
    $scope.hasNextPage = function(){
      return NewsComment.hasNextPage();
    }
    //请求网络数据完成之后
    $scope.$on('News.detailCommentUpdated', function() {
      Loading.hideLoading();
      $scope.newsCommentList = NewsComment.getCommentJson();
      $scope.memberInfo = NewsComment.getMemberInfo();
      $scope.messageTitle = NewsComment.getMessageTitleJson();
      $scope.$broadcast('scroll.refreshComplete');
    });
    $scope.$on('News.MoreDetailCommentUpdated',function(){
      $scope.newsCommentList = NewsComment.getCommentJson();
      $scope.$broadcast('scroll.infiniteScrollComplete');
    });
    //发表评论
    $scope.publishComment = function(){
      if($scope.comment.newComment == ''){
        Toast.showMessage("评论内容不能为空");
      }else{
        Loading.showLoading();
        NewsComment.publishComment(memberId,messageId,$scope.comment.newComment);
        $scope.comment.newComment = '';
      }
    }
    //请求网络数据完成之后
    $scope.$on('News.publishCommentUpdated', function() {
      Loading.hideLoading();
      var newComment = NewsComment.getNewComment();
      if(newComment.amCommentStatus){
        $scope.newsCommentList.unshift(newComment);
      }
      Toast.showMessage(newComment.amCommentMsg);
    });
  }).filter(
  'to_trusted', ['$sce', function ($sce) {
    return function (text) {
      return $sce.trustAsHtml(text);
    }
  }])
;
